import re

from rest_framework import serializers

from areas.models import Area, Address


class AreasSerializer(serializers.ModelSerializer):
    """
    省的序列化器
    """
    class Meta:
        model = Area
        fields = "__all__"


class AddressSerializer(serializers.ModelSerializer):
    # {"city": ["该字段是必填项。"], "province": ["该字段是必填项。"], "district": ["该字段是必填项。"]}
    district = serializers.StringRelatedField(read_only=True)
    city= serializers.StringRelatedField(read_only=True)
    province=serializers.StringRelatedField(read_only=True)
    district_id =serializers.IntegerField(min_value=1,write_only=True)
    city_id = serializers.IntegerField(min_value=1,write_only=True)
    province_id =serializers.IntegerField(min_value=1,write_only=True)

    class Meta:
        model = Address
        exclude = ("user",)

    def validate_mobile(self,value):
        if not re.match(r"1[3-9]\d{9}$",value):
            raise serializers.ValidationError("手机号格式错误")
        return value

    def create(self, validated_data):
        """
        因为返回的字段中没有user，所以需要保存的时候创造user
        :param validated_data:
        :return:
        """
        validated_data["user"] = self.context["request"].user
        # 这里不需要在像user.token = token 一样，因为这是向前端发送数据，而user 需要向数据库中添加数据，向后端推送数据
        address = super().create(validated_data)
        return address